from http.server import BaseHTTPRequestHandler, HTTPServer
import json

class RequestHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path == '/file':
            # 读取请求体中的内容
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            
            # 解析JSON数据
            try:
                data = json.loads(post_data.decode('utf-8'))
            except json.JSONDecodeError:
                self.send_error(400, "Invalid JSON format")
                return
            
            # 这里可以对data进行处理，然后生成txt文件的内容
            txt_content = "Received data: " + str(data)
            
            # 设置响应
            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            
            # 发送txt文件内容
            self.wfile.write(txt_content.encode('utf-8'))
        elif self.path=='/query':
                        # 设置响应
            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            self.wfile.write("test test".encode('utf-8'))
        else:
            self.send_error(404, "File not found")

def runWerServer(server_class=HTTPServer, handler_class=RequestHandler, port=8080):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    # print(f"Starting httpd server on port {port}")
    httpd.serve_forever()

if __name__ == '__main__':
    runWerServer()

# curl -X POST -H "Content-Type: application/json" -d "{'your_key': 'your_value'}" http://localhost:8080/query
# curl -X POST -H "Content-Type: application/json" -d '{"your_key": "your_value"}' http://localhost:8080/query